package com.zyj.test.month1.day7;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author Yijia Zhang
 * @create 2024-04-28 23:56
 */
public class code0015 {
    public List<List<Integer>> threeSum(int[] nums) {
        Arrays.sort(nums);
        int len = nums.length;
        List<List<Integer>> res = new ArrayList<>();
        for (int i = 0; i < len - 2 && nums[i] <= 0; i++) {
            while (i > 0 && i < len - 2 && nums[i] == nums[i - 1]) {
                i++;
            }
            if (i >= len - 2 || nums[i] > 0)
                break;
            int i1 = nums[i];
            int l = i + 1;
            int r = len - 1;
            int target = -i1;
            while (l < r) {
                int nowSum = nums[l] + nums[r];
                if (nowSum > target) {
                    int rv = nums[r];
                    while (l < r && nums[r] == rv) {
                        r--;
                    }
                } else if (nowSum < target) {
                    int lv = nums[l];
                    while (l < r && nums[l] == lv) {
                        l++;
                    }
                } else {
                    res.add(new ArrayList<Integer>(Arrays.asList(i1, nums[l], nums[r])));
                    int lv = nums[l];
                    int rv = nums[r];
                    while (l < r && nums[r] == rv) {
                        r--;
                    }
                    while (l < r && nums[l] == lv) {
                        l++;
                    }
                }
            }

        }
        return res;
    }
}
